<?php

namespace app\api\controller;

use app\common\model\CommonModel;
use think\Controller;
use think\Db;

class UserLogin extends Controller
{
    public function index()
    {
        if (request()->isPost()) {
            $param = input('param.');
            $sql =  Db::table('cms_blog_user')->where('account', $param['account'])->column('id,account,password');
            if (empty($sql)) {
                return json_encode(['code' => 0, 'msg' => '用户名不存在']);
            }
            foreach ($sql as $res) {
                $password = (new CommonModel())->thinkDecrypt($res['password']);
                if ($res['account'] == $param['account'] && $password == $param['password']) {
                    $token = $this->makeToken();
                    $data = [
                        'token' => $token,
                        'login_time' => time() + 604800 //token7天后过期
                    ];
                    Db::table('cms_blog_user')->where('id', $res['id'])->update($data);
                    return json_encode(['code' => 200, 'msg' => '登录成功', 'data' => $data]);
                } else {
                    return json_encode(['code' => 0, 'msg' => '用户名或者密码错误']);
                }
            }
        }
    }

    private function makeToken()
    {
        $str = md5(uniqid(md5(microtime(true)), true)); //生成一个不会重复的字符串
        $str = sha1($str); //加密
        return $str;
    }


}